package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.consts.Const;
import com.example.demo.dto.MomentDetailDTO;
import com.example.demo.entity.Comment;
import com.example.demo.entity.Moment;
import com.example.demo.entity.ReciteNum;
import com.example.demo.entity.User;
import com.example.demo.mapper.CommentMapper;
import com.example.demo.mapper.MomentMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.CommunityService;
import com.example.demo.utils.ContextUtils;
import com.example.demo.utils.HttpContextUtils;
import com.example.demo.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class CommunityServiceImpl implements CommunityService {

    @Resource
    private MomentMapper momentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private RedisTemplate<String, Integer> redisTemplate;


    @Override
    public Integer insertMoments(Moment moment) {
        Integer userId = moment.getUserId();
        User user = userMapper.selectById(userId);
        moment.setUsername(user.getUsername());
        moment.setAvatar(user.getImgUrl());
        return momentMapper.insert(moment);
    }

    @Override
    public List<Moment> selectAll(Integer pageNo) {
        QueryWrapper<Moment> wrapper = new QueryWrapper();
        /*0为不私密*/
        wrapper.eq("private_flag",0).orderByDesc("create_time");
        Page<Moment> page = new Page<>(pageNo, Const.PAGE_SIZE);
        IPage<Moment> userIPage = momentMapper.selectPage(page,wrapper);
        List<Moment> records = userIPage.getRecords();
        for (Moment record : records) {
            Integer likeCount = redisTemplate.opsForValue().get(Const.MOMENT_LIKE+"_"+record.getId());
            if(likeCount!=null){
                record.setLikeCount(likeCount);
            }
        }
        return records;
    }



    @Override
    public Result insertPic(MultipartFile avatar) {
        Map<String,Object> map = new HashMap<>();
        if (avatar.isEmpty()) {
            return Result.error("传入的图片有误");
        }else {
            //保存时的文件名
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar calendar = Calendar.getInstance();
            String dateName = df.format(calendar.getTime())+avatar.getOriginalFilename();
            //保存文件的绝对路径
            WebApplicationContext webApplicationContext = (WebApplicationContext) ContextUtils.getContext();
            ServletContext servletContext = webApplicationContext.getServletContext();
            String realPath = servletContext.getRealPath("/");
            String filePath = realPath + "WEB-INF"+ File.separator + "classes" + File.separator +"static" + File.separator + "resource" + File.separator+dateName;//此路径是放在tomcat war包的绝对路径
            File newFile = new File(filePath);
            boolean flag = newFile.mkdirs();
            System.out.println("filePath=:"+filePath);
            //MultipartFile的方法直接写文件
            try {
                //上传文件
                avatar.transferTo(newFile);
                //数据库存储的相对路径
                String projectPath = servletContext.getContextPath();
                HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
                String contextPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+projectPath;
                String url = contextPath + "/resource/"+dateName;//此路径是放在tomcat war包的相对路径
                //文件名与文件URL存入数据库表
                log.info("url={}",url);
                map.put("imageUrl",url);//返回前台
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        return Result.ok().data(map);
    }

    @Override
    public List<Moment> findByContentPart(String contentPart,Integer pageNo) {
        QueryWrapper<Moment> wrapper = new QueryWrapper();
        wrapper.like("content",contentPart).eq("private_flag",0).orderByDesc("create_time");
        Page<Moment> page = new Page<>(pageNo, Const.PAGE_SIZE);
        IPage<Moment> momentIPage = momentMapper.selectPage(page, wrapper);
        List<Moment> records = momentIPage.getRecords();
        for (Moment record : records) {
            Integer likeCount = redisTemplate.opsForValue().get(Const.MOMENT_LIKE+"_"+record.getId());
            if(likeCount!=null){
                record.setLikeCount(likeCount);
            }
        }
        return records;
    }

    @Override
    public List<Moment> findMyMoment(Long userId, Integer pageNo) {
        QueryWrapper<Moment> wrapper = new QueryWrapper();
        wrapper.eq("user_id",userId).orderByDesc("create_time");
        Page<Moment> page = new Page<>(pageNo, Const.PAGE_SIZE);
        IPage<Moment> momentIPage = momentMapper.selectPage(page, wrapper);
        List<Moment> records = momentIPage.getRecords();
        for (Moment record : records) {
            Integer likeCount = redisTemplate.opsForValue().get(Const.MOMENT_LIKE+"_"+record.getId());
            if(likeCount!=null){
                record.setLikeCount(likeCount);
            }
        }
        return records;
    }

    @Override
    public MomentDetailDTO selectMomentDetail(Long id,Integer pageNo) {
        /*第一步查询出该动态本身*/
        Moment moment = momentMapper.selectById(id);
        Integer likeCount = redisTemplate.opsForValue().get(Const.MOMENT_LIKE+"_"+moment.getId());
        if(likeCount!=null){
            moment.setLikeCount(likeCount);
        }
        /*第二步查出该动态对应的评论*/
        QueryWrapper<Comment> wrapper = new QueryWrapper();
        wrapper.eq("object_id",id).eq("type",Const.MOMENT_TYPE).orderByDesc("create_time");
        Page<Comment> page = new Page<>(pageNo, Const.PAGE_SIZE);
        IPage<Comment> commentIPage = commentMapper.selectPage(page, wrapper);
        List<Comment> records = commentIPage.getRecords();
        for (Comment record : records) {
            Integer likeNum = redisTemplate.opsForValue().get(Const.COMMENT_LIKE+"_"+record.getId());
            if(likeNum!=null){
                record.setLikeCount(likeNum);
            }
        }
        return new MomentDetailDTO(moment,records);
    }

    @Override
    public List<ReciteNum> getRank() {
        return momentMapper.selectRank();
    }
}
